<?php

namespace App\Http\Services;

use Illuminate\Support\Facades\DB;

class ToolsService
{
    public static function saveRequestInfo($data)
    {
        $isSave = $data['is_save'];
        unset($data['is_save']);
        $isSave && DB::table('sa_request_ip_logs')->insert($data);

        return $data;
    }

    /**
     * webhook  触发.
     *
     * @param $payload
     *
     * @return void
     */
    public static function giteeWebhook($payload)
    {
        $secret    = config('auth.webhook_secret'); // 与Gitee设置的密钥一致
        $signature = $_SERVER['HTTP_X_GITEE_TOKEN'] ?? '';

        if ($signature !== $secret) {
            header('HTTP/1.0 403 Forbidden');
            exit('Invalid secret');
        }

        // 验证是push事件且是master分支
        $data = json_decode($payload, true);
        if (isset($data['ref']) && 'refs/heads/master' === $data['ref']) {
            // 执行拉取脚本
            $output = shell_exec(storage_path('script/webhook_pull_master.sh') . ' 2>&1');

            // 记录日志（可选）
            file_put_contents(
                storage_path('logs/webhook.log'),
                date('Y-m-d H:i:s') . ' - ' . $output . "\n",
                FILE_APPEND
            );

            // 返回输出
            echo $output;
        } else {
            echo 'Not master branch push, ignored';
        }
    }
}
